package com.example.dingtalk.controller;


import com.aliyun.dingtalkworkflow_1_0.models.*;
import com.example.dingtalk.entity.Approve;
import com.example.dingtalk.entity.Form;
import com.example.dingtalk.entity.User;
import com.example.dingtalk.service.impl.OaServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/5/22
 */

@RestController
@Slf4j
@RequestMapping("oa")
public class OaController {

    @Autowired
    private OaServiceImpl oaService;

    /**
     * 用户提交审批
     *
     * @throws Exception
     */
    @GetMapping("commitApprove")
    public void commitApprove() throws Exception {
        Form form = new Form().setNameFirst("补卡时间").setValueFirst("2024-05-23");
        User user = new User().setUserId("manager6924").setDeptId(1L);
        oaService.commitApprove(user, form);
    }

    /**
     * 根据实例id获取审批实例详情
     * @param processInstanceId
     * @throws Exception
     */
    @GetMapping("getProcessInstance")
    public void getProcessInstance(String processInstanceId) throws Exception {
        GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
        log.info("该审批实例的状态为：" + processInstance.getBody().getResult().getStatus());
        log.info("taskid: " + processInstance.getBody().getResult().getTasks().get(0).getTaskId());
    }


    /**
     * 管理者审批
     * @throws Exception
     */
    @GetMapping("executeProcessInstance")
    public void executeProcessInstance() throws Exception {
        String processInstanceId = "ckmTE21tRXiYUAIDTFeD8A09171716538659";
        GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
        log.info("taskid: " + processInstance.getBody().getResult().getTasks().get(0).getTaskId());
        Approve approve = new Approve().setTaskId(processInstance.getBody().getResult().getTasks().get(0).getTaskId()).setProcessInstanceId(processInstanceId).setResult("agree").setUserId("manager6924");
//        Approve approve = new Approve().setTaskId(processInstance.getBody().getResult().getTasks().get(0).getTaskId()).setProcessInstanceId(processInstanceId).setResult("refuse").setComment("亲自过来说").setUserId("manager6924");
        oaService.executeProcessInstance(approve);
    }


    /**
     * 根据审批人查询待办审批流
     * @throws Exception
     */
    @GetMapping("getProcessListByApprover")
    public void getProcessListByPage() throws Exception {
        User user = new User().setUserId("manager6924");

        // 获取所有审批实例ID列表
        ArrayList<String> processInstanceIdList = new ArrayList<>();
        // 每页大小
        Long pageSize = 20L;
        // 待办审批流状态: RUNNING、TERMINATED、COMPLETED
//        String statuses = "RUNNING";
        String statuses = "COMPLETED";


        // 获取查询的起始时间，默认结束时间是函数调用时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // 往前推3个月
        c.add(Calendar.MONTH, -3);
        Date time = c.getTime();

        // 获取审批模板code
        String processCode = "PROC-3915C166-DD31-422F-935D-58C1ACC14F7F";
        ListProcessInstanceIdsResponseBody.ListProcessInstanceIdsResponseBodyResult result = oaService.getProcessListByPage(time.getTime(), processCode, 1L, pageSize, statuses);

        if (result != null) {
            result.getList().forEach(processInstanceId -> {
                try {
                    GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
                    if (processInstance.getBody().getResult().getApproverUserIds() != null && processInstance.getBody().getResult().getApproverUserIds().contains(user.getUserId())) {
                        processInstanceIdList.add(processInstanceId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (result.getNextToken() != null) {
                result = oaService.getProcessListByPage(time.getTime(), processCode, Long.valueOf(result.getNextToken()), pageSize, statuses);
                result.getList().forEach(processInstanceId -> {
                    try {
                        GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
                        if (processInstance.getBody().getResult().getApproverUserIds() != null && processInstance.getBody().getResult().getApproverUserIds().contains(user.getUserId())) {
                            processInstanceIdList.add(processInstanceId);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        }

        processInstanceIdList.forEach(processInstanceId -> {
                    log.info("审批流列表：" + processInstanceId);
                }
        );
        log.info("审批流列表数量：" + processInstanceIdList.size());
    }


    /**
     * 根据用户查询审批流
     */
    @GetMapping("getProcessListByUser")
    public void getProcessListByUser() throws Exception {
        User user = new User().setUserId("manager6924");

        // 获取所有审批实例ID列表
        ArrayList<String> processInstanceIdList = new ArrayList<>();
        // 每页大小
        Long pageSize = 20L;
        // 待办审批流状态: RUNNING、TERMINATED、COMPLETED
//        String statuses = "RUNNING";
        String statuses = "RUNNING";


        // 获取查询的起始时间，默认结束时间是函数调用时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // 往前推3个月
        c.add(Calendar.MONTH, -3);
        Date time = c.getTime();

        // 获取审批模板code
        String processCode = "PROC-3915C166-DD31-422F-935D-58C1ACC14F7F";
        ListProcessInstanceIdsResponseBody.ListProcessInstanceIdsResponseBodyResult result = oaService.getProcessListByPage(time.getTime(), processCode, 1L, pageSize, statuses);

        if (result != null) {
            result.getList().forEach(processInstanceId -> {
                try {
                    GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
                    if (Objects.equals(processInstance.getBody().getResult().getOriginatorUserId(), user.getUserId())){
                        processInstanceIdList.add(processInstanceId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (result.getNextToken() != null) {
                result = oaService.getProcessListByPage(time.getTime(), processCode, Long.valueOf(result.getNextToken()), pageSize, statuses);
                result.getList().forEach(processInstanceId -> {
                    try {
                        GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
                        if (Objects.equals(processInstance.getBody().getResult().getOriginatorUserId(), user.getUserId())){
                            processInstanceIdList.add(processInstanceId);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        }

        processInstanceIdList.forEach(processInstanceId -> {
                    log.info("审批流列表：" + processInstanceId);
                }
        );
        log.info("审批流列表数量：" + processInstanceIdList.size());
    }


}
